'use client'
import {
   MenuFoldOutlined,
   HomeOutlined,
   PoweroffOutlined,
   MenuUnfoldOutlined,
   FileOutlined,
   DownOutlined,
   UserOutlined,
   BookOutlined,
} from '@ant-design/icons';
import { Layout, Menu, Dropdown, MenuProps, Button, Input, Popconfirm, Table, Modal, message, Form, ConfigProvider } from 'antd';
import type { TableColumnsType, GetRef, PopconfirmProps, InputRef } from 'antd';
import type { TableProps } from 'antd';
import type { PaginationProps } from 'antd';
import React, { useState, ChangeEvent, useEffect, useRef, useContext } from 'react';
import type { DraggableData, DraggableEvent } from 'react-draggable';
import Draggable from 'react-draggable';
import { useRouter } from 'next/navigation'
import zhCN from 'antd/es/locale/zh_CN';
import Link from 'next/link';
import { getCookie } from '../utils'
const { Header, Sider, Content } = Layout;
interface DataType {
   toid: number,
   toname: string;
   toabbreviation: string;
   todataNumber: number;
   tomodifytime: string,
   tocreatetime: string;
   tolelvel1: string,
   tolelvel2: string,
   tolelvel3: string,
   tolelvel4: string,
   tolelvel5: string,
   tostatus: string,
   todescription: string
}
interface DataModalType {
   flag?: string,
   twid: string,
   twname: string;
   twoname: string;
}

const showTotal: PaginationProps['showTotal'] = (total) => `一共 ${total} 条`;
const DataClub: React.FC = () => {
   const [collapsed, setCollapsed] = useState(false);
   const [data, setData] = useState<DataType[]>([]);
   const [modaldata, setModaldata] = useState<DataModalType[]>([]);
   const [iputVal, setIputVal] = useState('');
   const [choseId, setChoseId] = useState(0);
   const useidRef = useRef(0)
   const [username, setUsername] = useState('');
   const [isModalOpen, setIsModalOpen] = useState(false);
   const [disabled, setDisabled] = useState(true);
   const [pagination, setPagination] = useState({
      current: 1,
      pageSize: 10,
      total: 1,
      showTotal,
      showSizeChanger: true
   })
   const [modalPagination, setModalPagination] = useState({
      current: 1,
      pageSize: 10,
      total: 1,
      showTotal,
      showSizeChanger: true
   })
   const [loading, setLoading] = useState(false)
   const useStateRef = useRef('')
   const draggleRef = useRef<HTMLDivElement>(null);
   const [bounds, setBounds] = useState({ left: 0, top: 0, bottom: 0, right: 0 });
   const onStart = (_event: DraggableEvent, uiData: DraggableData) => {
      const { clientWidth, clientHeight } = window.document.documentElement;
      const targetRect = draggleRef.current?.getBoundingClientRect();
      if (!targetRect) {
         return;
      }
      setBounds({
         left: -targetRect.left + uiData.x,
         right: clientWidth - (targetRect.right - uiData.x),
         top: -targetRect.top + uiData.y,
         bottom: clientHeight - (targetRect.bottom - uiData.y),
      });
   };
   const handleOk = () => {
      setIsModalOpen(false);
   };
   const handleAddFav = (id: number) => {
      fetch('/SWJDTXT/saveTowndsb?tnoid=' + id + '&tnman=' + username, { method: 'POST' }).then(res => {
         res.text().then(datas => {
            console.log(datas)
            if (datas == '成功') {
               message.success('添加成功');
            } else {
               message.error('添加失败！')
            }
         })
      })
   };
   const handleCancel = () => {
      setIsModalOpen(false);
   };
   const showNumbers = (id: number) => {
      // 点击弹框
      setIsModalOpen(true);
      setChoseId(() => {
         useidRef.current = id;
         return useidRef.current
      });
      setTimeout(() => {
         queryModalData(1)
      }, 0)
   }
   const queryModalData = (currentPage?: number, pageSizes?: number) => {
      // 只有点击查询才会从第一页显示，其他的都是按照pagination来显示
      let pageSize = pageSizes ? pageSizes : pagination.pageSize;
      let currentPages = currentPage ? currentPage : pagination.current;
      fetch(`/SWJDTXT/queryTwmand?twpage=${currentPages}&twoid=${useidRef.current}&twman=${useStateRef.current}&twpagesize=${pageSize}&twname=${iputVal}`, { method: 'POST' }).then(res => {
         let resultData = res.json()
         resultData.then(results => {
            if (results instanceof Array && results.length > 0) {
               let data = results[0].data;
               let total = results[0].total;
               setModalPagination({ total: total, current: currentPages, pageSize: pageSize, showTotal, showSizeChanger: true })
               setModaldata(data)
            }
         })
      })
   }
   const columns: TableColumnsType<DataType> = [
      {
         title: '数据集名称',
         dataIndex: 'toname',
         key: 'toname',
         width: 200,
         fixed: 'left',
      },
      {
         title: '缩写',
         width: 80,
         dataIndex: 'toabbreviation',
         key: 'toabbreviation'
      },
      {
         title: '数据量',
         dataIndex: 'todataNumber',
         key: 'todataNumber',
         width: 90,
         render: (_, record) => <Button type="link" onClick={(e) => showNumbers(record.toid)}>{record.todataNumber}</Button>,
      },
      {
         title: '数据创建时间',
         dataIndex: 'tocreatetime',
         key: 'totime',
         width: 120,
      },
      {
         title: '等级1',
         dataIndex: 'tolelvel1',
         key: 'tolelvel1',
         width: 70,
      },
      {
         title: '等级2',
         dataIndex: 'tolelvel2',
         key: 'tolelvel2',
         width: 70,
      },
      {
         title: '等级3',
         dataIndex: 'tolelvel3',
         key: 'tolelvel3',
         width: 70,
      },

      {
         title: '等级4',
         dataIndex: 'tolelvel4',
         key: 'tolelvel4',
         width: 70,
      },
      {
         title: '等级5',
         dataIndex: 'tolelvel5',
         key: 'tolelvel5',
         width: 70,
      },
      {
         title: '状态',
         dataIndex: 'tostatus',
         key: 'tostatus',
         width: 90,
         render: (_, record) => <div>
            {record.tostatus == '1' ? '已添加' : '未添加'}
         </div>
      },
      {
         title: '简介',
         dataIndex: 'todescription',
         key: 'todescription',
         width: 280,
      },
      {
         title: '操作',
         key: 'operation',
         fixed: 'right',
         width: 100,
         render: (_, record) => <Popconfirm
            title="温馨提示"
            description="你确定要添加这个数据集吗?"
            onConfirm={() => handleAddFav(record.toid)}
            okText="确定"
            cancelText="取消"
         >
            <Button type='primary' disabled={record.tostatus == '1'}>添加</Button>
         </Popconfirm>,
      },
   ];

   const columnModal: TableColumnsType<DataModalType> = [
      {
         title: '期刊名称',
         dataIndex: 'twname',
         key: 'twname',
         width: 200
      },
      {
         title: '缩写',
         width: 80,
         dataIndex: 'twoname',
         key: 'twoname'
      }]
   useEffect(() => {
      let usernames: string = getCookie('sjhm');
      // if (username == '') {
      // window.location.href="https://www.xsjxkt.com/qd/dl/login"
      // message.warning('请首先登录！');
      // return () => { }
      // }
      setUsername(() => {
         useStateRef.current = usernames;
         return useStateRef.current
      });
      setTimeout(() => {
         queryData();
      }, 500)
      return () => {
         // 组件即将卸载，这里可以做一些清理工作，如取消请求等
      };
   }, [])
   const queryData = (currentPage?: number, pageSizes?: number) => {
      setLoading(true)
      // 只有点击查询才会从第一页显示，其他的都是按照pagination来显示
      fetch(`/SWJDTXT/queryTnoid?tnman=${useStateRef.current}`, { method: 'POST' }).then(resNumber => {
         let resultNumber = resNumber.json()
         resultNumber.then(resultNumbers => {
            let numberId = resultNumbers[0].shuzi;
            let statusId = resultNumbers[0].status;// 这里只会放已经被添加的id;
            let pageSize = pageSizes ? pageSizes : pagination.pageSize;
            let currentPages = currentPage ? currentPage : pagination.current;
            fetch(`/SWJDTXT/queryTomands?topage=${currentPages}&topagesize=${pageSize}&toname=${iputVal}`, { method: 'POST' }).then(res => {
               let resultData = res.json()
               resultData.then(results => {
                  if (results instanceof Array && results.length > 0) {
                     let data = results[0].data;
                     let total = results[0].total;
                     if (data && data.length && data.length > 0) {
                        for (let ii = 0; ii < data.length; ii++) {
                           if (numberId && numberId.length && numberId.length > 0) {
                              for (let iis = 0; iis < numberId.length; iis++) {
                                 if (data[ii].toid == numberId[iis][0]) {
                                    data[ii].todataNumber = numberId[iis][1]
                                    break;
                                 }
                              }
                           }
                           if (statusId && statusId.length && statusId.length > 0) {
                              for (let iis = 0; iis < statusId.length; iis++) {
                                 if (data[ii].toid == statusId[iis]) {
                                    data[ii].tostatus = '1'
                                    break;
                                 }
                              }
                           } else {
                              data[ii].tostatus = '0'
                           }
                        }
                     }
                     setPagination({ total: total, current: currentPages, pageSize: pageSize, showTotal, showSizeChanger: true })
                     setData(data)
                     setLoading(false)
                  }
               })
            })
         })
      }).catch(()=>{
         setLoading(false)
      })

      // new Promise(resove => {
      //    let data = []
      //    let tempData: DataType = {
      //       toid: 1, toname: '国家自然科学基金委管理科学部认定的重要期刊',
      //       toabbreviation: '国自然管科', tocreatetime: '2024-01-01', tomodifytime: '2024-6-1', todataNumber: 4,
      //       tolelvel1: '1', tolelvel2: '1', tolelvel3: '1', tolelvel4: '1', tolelvel5: '1', tostatus: '0',
      //       todescription: '国家自然科学基金委管理科学部认定的重要期刊，一共有30本期刊，22本A，8本B 。'
      //    }
      //    for (let ii = 0; ii < 10; ii++) {
      //       let copyData: DataType = JSON.parse(JSON.stringify(tempData))
      //       copyData.toid += tempData.toid + ii;
      //       ii % 2 == 0 ? copyData.tostatus = '0' : copyData.tostatus = '1'
      //       data.push(copyData)
      //    }
      //    let res = { code: 200, data: { total: 10, list: data } }
      //    resove(res)
      // }).then((res) => {   
      // })
   }
   const changeInputVal = (event: ChangeEvent<HTMLInputElement>) => {
      setIputVal(event.target.value);
   };
   const router = useRouter()
   function onClick(obj: { key: string }) {
      if (obj.key === '1') {
         // 跳转到官网
         window.open('https://www.xsjxkt.com/', '_blank')
      } else {
         // 退出登录
      }
   };
   const onClickMenu: MenuProps['onClick'] = e => {
      if (e.key == '11') {
         // 跳转到用户信息-我的信息页面
         router.push('/user')
      } else if (e.key == '2') {
         // 跳转到自定义数据集-文献管理页面
         router.push('/paperMgt')
      } else if (e.key == '32') {
         // 跳转到自定义数据集-已选数据集页面
         router.push('/dataChosen')
      } else if (e.key == '33') {
         // 跳转到自定义数据集-编辑数据集页面
         router.push('/editData')
      }
   };
   const items = [{
      key: '1',
      label: (
         <div>
            <HomeOutlined /><span style={{ marginLeft: 6 }}>回到官网</span>
         </div>
      ),
   }]
   const handleTableChange = (pagination: TableProps<DataType>['pagination']) => {
      if (pagination) {
         setPagination({ total: pagination.total ? pagination.total : 0, current: pagination.current ? pagination.current : 1, pageSize: pagination.pageSize ? pagination.pageSize : 10, showTotal, showSizeChanger: true })
      }
      if (pagination && pagination.current && pagination.pageSize) {
         queryData(pagination.current, pagination.pageSize)
      }
   }
   const handleModalChange = (pagination: TableProps<DataType>['pagination']) => {
      if (pagination) {
         setModalPagination({ total: pagination.total ? pagination.total : 0, current: pagination.current ? pagination.current : 1, pageSize: pagination.pageSize ? pagination.pageSize : 10, showTotal, showSizeChanger: true })
      }
      if (pagination && pagination.current) {
         queryModalData(pagination.current, pagination.pageSize)
      }
   }
   return <Layout style={{ height: '100%' }}>
      <Sider style={{ backgroundColor: '#ffffff' }} trigger={null} collapsible collapsed={collapsed}>
         <div className="logo" />
         <Menu style={{ backgroundColor: '#ffffff', borderRight: '1px solid #0505050f' }}
            theme="light"
            onClick={onClickMenu}
            mode="inline"
            defaultOpenKeys={['3']}
            defaultSelectedKeys={['31']}
            items={[
               // {
               //    key: '1',
               //    icon: <UserOutlined />,
               //    label: '用户信息',
               //    children: [
               //       {
               //          key: '11',
               //          label: '我的信息',
               //       },
               //    ]
               // },
               {
                  key: '2',
                  icon: <BookOutlined />,
                  label: '文献管理',
               },
               {
                  key: '3',
                  icon: <FileOutlined />,
                  label: '自定义数据集',
                  children: [
                     {
                        key: '31',
                        label: '数据集社区',
                     },
                     {
                        key: '32',
                        label: '我的数据集',
                     }
                  ]
               },
            ]}
         />
      </Sider>
      <Layout className="site-layout" style={{ backgroundColor: '#fff' }}>
         <Header className="site-layout-background" style={{ backgroundColor: '#ffffff', paddingLeft: 12 }}>
            {React.createElement(collapsed ? MenuUnfoldOutlined : MenuFoldOutlined, {
               className: 'trigger',
               onClick: () => setCollapsed(!collapsed),
            })}
            <div style={{ float: 'right' }}>
               <Dropdown menu={{ items, onClick }}>
                  <a onClick={e => e.preventDefault()}>
                     <UserOutlined /> {username}
                     <DownOutlined style={{ marginLeft: 8 }} />
                  </a>
               </Dropdown>
            </div>
         </Header>
         <Content
            className="site-layout-background"
            style={{
               padding: 12,
               background: 'rgba(0, 0, 0, 0.05)',
               borderRadius: 4
            }}
         >
            <div style={{
               padding: 12,
               background: '#fff',
               borderRadius: 4,
               height: '100%'
            }}>
               <div style={{ marginBottom: 6 }} className='p-1 bg-white'>
                  <Input style={{ display: 'inline-block', width: 240}} placeholder="数据集名称" value={iputVal} onChange={changeInputVal} defaultValue="" />
                  <Button type="primary" style={{ margin: '0 6px' }} onClick={() => { queryData(1) }} autoInsertSpace>
                     查询
                  </Button>
               </div>
               <ConfigProvider locale={zhCN}>
                  <Table
                     size="small"
                     columns={columns}
                     pagination={pagination}
                     bordered
                     onChange={handleTableChange}
                     dataSource={data}
                     rowKey={(record) => record.toid}
                     sticky={{ offsetHeader: 64 }}
                  />
               </ConfigProvider>
            </div>
         </Content>
      </Layout>
      <Modal title={
         <div
            style={{
               width: '100%',
               cursor: 'move',
            }}
            onMouseOver={() => {
               if (disabled) {
                  setDisabled(false);
               }
            }}
            onMouseOut={() => {
               setDisabled(true);
            }}
            onFocus={() => { }}
            onBlur={() => { }}
         // end
         >
            查看数据集期刊详情
         </div>
      } footer={null} width={900} open={isModalOpen} onOk={handleOk} onCancel={handleCancel} modalRender={(modal) => (
         <Draggable
            disabled={disabled}
            bounds={bounds}
            nodeRef={draggleRef}
            onStart={(event, uiData) => onStart(event, uiData)}
         >
            <div ref={draggleRef}>{modal}</div>
         </Draggable>
      )}>
         <div>
            <div>
               <Input style={{ display: 'inline-block', width: 240, marginLeft: 6, marginBottom: 12 }} placeholder="期刊名称" value={iputVal} onChange={changeInputVal} defaultValue="" />
               <Button type="primary" style={{ margin: '0 6px' }} onClick={(e) => queryModalData()} autoInsertSpace>
                  查询
               </Button>
               {/* <Button type="primary" style={{ margin: '0 6px' }} onClick={(e) => saveModalData()} autoInsertSpace>
                     保存数据
                  </Button> */}
            </div>
            <ConfigProvider locale={zhCN}>
               <Table
                  size="small"
                  columns={columnModal}
                  bordered
                  onChange={handleModalChange}
                  pagination={modalPagination}
                  dataSource={modaldata}
                  loading={loading}
                  rowKey={(record) => record.twid}
                  sticky={{ offsetHeader: 64 }}
               />
            </ConfigProvider>
         </div>
      </Modal>
   </Layout>
};

export default DataClub;